import { useState, useRef } from 'react';
import { Play, Pause, Volume2, VolumeX, Square, RotateCcw, RotateCw } from 'lucide-react';
import { useAppDispatch, useAppSelector } from '@/store';
import { setCurrentTime, setPlaybackState, setPlaybackRate } from '@/store/slices/timelineSlice';

interface PreviewPlayerProps {
  className?: string;
}

const PreviewPlayer: React.FC<PreviewPlayerProps> = ({ className }) => {
  const dispatch = useAppDispatch();
  const { isPlaying, currentTime, duration, playbackRate, clips } = useAppSelector(
    state => state.timeline
  );

  const [volume, setVolume] = useState(1);
  const [isMuted, setIsMuted] = useState(false);
  // const [isFullscreen, setIsFullscreen] = useState(false);
  const videoRef = useRef<HTMLVideoElement>(null);

  // 处理播放控制
  const handlePlayPause = () => {
    if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.pause();
        dispatch(setPlaybackState(false));
      } else {
        videoRef.current.play();
        dispatch(setPlaybackState(true));
      }
    }
  };

  // 处理时间更新
  const handleTimeUpdate = () => {
    if (videoRef.current) {
      dispatch(setCurrentTime(videoRef.current.currentTime));
    }
  };

  // 处理播放结束
  const handleEnded = () => {
    dispatch(setPlaybackState(false));
    dispatch(setCurrentTime(0));
  };

  // 处理音量控制
  const handleVolumeChange = (newVolume: number) => {
    setVolume(newVolume);
    if (videoRef.current) {
      videoRef.current.volume = newVolume;
      setIsMuted(newVolume === 0);
    }
  };

  // 处理静音切换
  const handleMuteToggle = () => {
    const newMuted = !isMuted;
    setIsMuted(newMuted);
    if (videoRef.current) {
      videoRef.current.muted = newMuted;
    }
  };

  // 处理播放速率
  const handlePlaybackRateChange = (rate: number) => {
    dispatch(setPlaybackRate(rate));
    if (videoRef.current) {
      videoRef.current.playbackRate = rate;
    }
  };

  // 处理跳转
  const handleSeek = (time: number) => {
    if (videoRef.current) {
      videoRef.current.currentTime = Math.max(0, Math.min(time, duration));
      dispatch(setCurrentTime(videoRef.current.currentTime));
    }
  };

  // 快进/快退
  const handleFastForward = (seconds: number) => {
    handleSeek(currentTime + seconds);
  };

  // 格式化时间
  const formatTime = (seconds: number): string => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  // 渲染播放状态指示器
  const renderPlaybackStatus = () => {
    if (clips.length === 0) {
      return (
        <div className='preview-placeholder'>
          <div className='placeholder-icon'>
            <Square size={48} />
          </div>
          <p className='placeholder-text'>导入视频开始预览</p>
          <p className='placeholder-subtext'>将视频拖放到时间线或点击导入按钮</p>
        </div>
      );
    }

    // 模拟视频预览（实际项目中应该播放真实视频）
    return (
      <div className='preview-video'>
        <div className='video-container'>
          <video
            ref={videoRef}
            className='preview-element'
            onTimeUpdate={handleTimeUpdate}
            onEnded={handleEnded}
            muted={isMuted}
            playsInline
          >
            {/* 实际项目中应该设置真实的视频源 */}
            <source src='' type='video/mp4' />
            您的浏览器不支持视频播放。
          </video>

          {/* 播放状态指示器 */}
          <div className='playback-overlay'>
            {!isPlaying && clips.length > 0 && (
              <button className='play-button' onClick={handlePlayPause}>
                <Play size={48} />
              </button>
            )}

            {/* 播放速率指示器 */}
            {playbackRate !== 1 && <div className='playback-rate-indicator'>{playbackRate}x</div>}
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className={`preview-player ${className || ''}`}>
      {/* 预览区域 */}
      <div className='preview-area'>{renderPlaybackStatus()}</div>

      {/* 播放控制栏 */}
      <div className='playback-controls'>
        {/* 播放控制按钮 */}
        <div className='control-group'>
          <button
            className='control-btn'
            onClick={() => handleFastForward(-5)}
            disabled={clips.length === 0}
            title='后退5秒'
          >
            <RotateCcw size={16} />
          </button>

          <button
            className='control-btn play-pause-btn'
            onClick={handlePlayPause}
            disabled={clips.length === 0}
          >
            {isPlaying ? <Pause size={20} /> : <Play size={20} />}
          </button>

          <button
            className='control-btn'
            onClick={() => handleFastForward(5)}
            disabled={clips.length === 0}
            title='前进5秒'
          >
            <RotateCw size={16} />
          </button>
        </div>

        {/* 时间显示 */}
        <div className='time-display'>
          <span className='current-time'>{formatTime(currentTime)}</span>
          <span className='time-separator'>/</span>
          <span className='total-time'>{formatTime(duration)}</span>
        </div>

        {/* 进度条 */}
        <div className='progress-container'>
          <input
            type='range'
            min={0}
            max={duration || 100}
            value={currentTime}
            onChange={e => handleSeek(Number(e.target.value))}
            className='progress-slider'
            disabled={clips.length === 0}
          />
          <div
            className='progress-bar'
            style={{ width: `${(currentTime / (duration || 1)) * 100}%` }}
          />
        </div>

        {/* 音量控制 */}
        <div className='volume-controls'>
          <button
            className='control-btn'
            onClick={handleMuteToggle}
            title={isMuted ? '取消静音' : '静音'}
          >
            {isMuted ? <VolumeX size={16} /> : <Volume2 size={16} />}
          </button>

          <input
            type='range'
            min={0}
            max={1}
            step={0.1}
            value={volume}
            onChange={e => handleVolumeChange(Number(e.target.value))}
            className='volume-slider'
          />
        </div>

        {/* 播放速率 */}
        <div className='playback-rate-controls'>
          <select
            value={playbackRate}
            onChange={e => handlePlaybackRateChange(Number(e.target.value))}
            className='rate-select'
            disabled={clips.length === 0}
          >
            <option value={0.25}>0.25x</option>
            <option value={0.5}>0.5x</option>
            <option value={0.75}>0.75x</option>
            <option value={1}>1x</option>
            <option value={1.25}>1.25x</option>
            <option value={1.5}>1.5x</option>
            <option value={2}>2x</option>
          </select>
        </div>
      </div>
    </div>
  );
};

export default PreviewPlayer;
